#!/bin/bash

FILE_PATH=/opt/etcloud/damon_log/

mkdir -p $FILE_PATH

LOG_FILE=$FILE_PATH/demon.log


port_telnet(){
		LOCALHOST=$1
		PORT=$2
		if [[ echo >/dev/tcp/$LOCALHOST/$PORT ]]; then
			echo true
		else
			echo false
		fi
}

send_mail(){
	IP=`cat ip.config`
	for TO in `cat mail_list.config`
	do
		./send_mail --to="$TO" --subject="$1" --body="ip:$IP $2"
	done
}

LOG_SERVER=false
IM_SERVER=false
HAM_SERVER=false
DEBUG=false

echo `port_telnet 127.0.0.1 1883`

for SERVER in `cat ./demon_config` 
do
	echo $SERVER
	if [[ "$SERVER" == im_server ]]; then
		IM_SERVER=true
	elif [[ "$SERVER" == "log_server" ]]; then
		LOG_SERVER=true
	elif [[ "$SERVER" == "ham_server" ]] ; then
		HAM_SERVER=true
	fi
done

debug(){
	if [[ $DEBUG == true ]]; then
		echo $@
	fi
}

echo "monitor $LOG_SERVER,$IM_SERVER,$HAM_SERVER"

while true
do
	if [[ $IM_SERVER == true ]]; then
		debug " im_server loop monitor "
		if (( `ps -ef | grep 'im_server/erts-8.0/bin/beam.smp' | grep -v grep | wc -l` <= 0 )); then
			echo "im_server done $`date `" >> 	$LOG_FILE
			send_mail "im monitor" "the im_server restart"
			/opt/etcloud/im_server/bin/im_server start
		fi
	fi

	if [[ $LOG_SERVER == true ]]; then
		debug " log_server loop monitor "
		if (( `ps -ef | grep 'log_server/erts-8.0/bin/beam' | grep -v grep | wc -l` <= 0 )); then
			echo "log_server done $`date `" >> 	$LOG_FILE
			/opt/etcloud/log_server/bin/log_server start
			send_mail "im monitor" "the log_server restart"
		fi
	fi


	if [[ $HAM_SERVER == true ]]; then
		debug " ham_server loop monitor "
		if (( `ps -ef | grep 'ham_server/erts-8.0/bin/beam' | grep -v grep | wc -l` <= 0 )); then
			echo "ham_server done $`date `" >> 	$LOG_FILE
			/opt/etcloud/ham_server/bin/ham_server start
			send_mail "im monitor" "the ham_server restart"
		fi
	fi

	MQTT_PING=`./mqtt_client --host="119.29.7.247:1883" --user="ping_user_cym"` 
	echo "mqtt connecting $MQTT_PING"
	if [[ $MQTT_PING != "mqtt_succ" ]] ; then
		echo "MQTT_PING error $MQTT_PING" >> $LOG_FILE
		send_mail "im monitor" "connecting mqtt error. $MQTT_PING"
	fi

	sleep 5
done

